<script>
	import homeApi from "@/api/home.js"
	export default {
		data() {
			return {
				zim: null,
			};
		},
		onLaunch: function() {
			console.log('App Launch')
			if (uni.getStorageSync('token')) {
				setTimeout(() => {
					this.getUserInfo()
				}, 1000)
			}
		},
		onShow: function() {
			console.log('App Show')
		},
		onHide: function() {
			console.log('App Hide')
		},
		methods: {
			getUserInfo() {
				homeApi.getUserInfo().then(res => {
					let that = this
					if (res.code === 1) {
						uni.setStorageSync('userInfo', res.data)
						this.$store.state.userInfo = res.data
						this.$store.dispatch('createZIM').then((zim_x) => {
							that.getZIM(res.data, that);
						});
					}
				})
			},

			getZIM(userInfo, that) {
				// 注册监听“运行时错误信息”的回调
				that.$store.state.zim.on("error", function(zim, errorInfo) {
					// console.log("error", errorInfo.code, errorInfo.message);
				});

				// 更新会话列表
				that.$store.state.zim.on("conversationChanged", function(zim, {
					infoList
				}) {
					console.log("更新会话列表conversationChanged", infoList);
					that.$store.commit('updata_ConversationList', infoList)
				});

				// 注册监听“网络连接状态变更”的回调
				that.$store.state.zim.on(
					"connectionStateChanged",
					function(zim, {
						state,
						event,
						extendedData
					}) {
						// console.log(
						//     "connectionStateChanged",
						//     state,
						//     event,
						//     extendedData
						// );
						// 当长时间网络连接断开导致SDK内部登出时，需要重新登录
						if (state == 0 && event == 3) {
							// zim.login(userInfo, token);
							console.log("网络连接状态变更");
							that.$store.dispatch('ZIMLogin')
						}
					}
				);

				// 注册监听“令牌即将过期”的回调
				that.$store.state.zim.on("tokenWillExpire", function(zim, {
					second
				}) {
					// console.log("令牌即将过期", second);
					// 可以在这里调用 renewToken 接口来更新 token
					// 新 token 生成可以参考上文
					let token = uni.getStorageSync("zegoToken");
					uni.removeStorageSync("zegoToken");
					zim.renewToken(token)
						.then(function({
							token
						}) {
							// 更新成功
							uni.setStorageSync("zegoToken", token);
							that.$store.dispatch('ZIMLogin')
						})
						.catch(function(err) {
							// 更新失败
							that.$store.dispatch('ZIMLogin')
						});
				});
				
				
				that.$store.dispatch('ZIMLogin')
			},

		}
	}
</script>

<style lang="scss">
	/* 注意要写在第一行，同时给style标签加入lang="scss"属性 */
	@import "@/uni_modules/uview-ui/index.scss";
	/*每个页面公共css */
	@import "colorui/main.css";
	@import "colorui/icon.css";
</style>